<?php
	include '../include/functions.php';
//set session save path
session_save_path("../".$session_path);
// Initialize a session. 
session_start();
$count++;
$start = time();
$sessionId = session_id();

?>
<!DOCTYPE html PUBLIC "-//W3C//Dtd html 4.01 Transitional//EN"
"http://www.w3.org/tr/html4/loose.dtd">
<html>
  <head>
  <title>JoshHughes.com AFL Football Pool</title>
	<link rel="stylesheet" href="http://football.joshhughes.com/css/AFL.css" type="text/css">
    <script src="http://football.joshhughes.com/scripts/prototype.js" type="text/javascript"></script>
	<script src="http://football.joshhughes.com/scripts/scriptaculous.js" type="text/javascript"></script>
	<script src="http://football.joshhughes.com/scripts/football.js" type="text/javascript"></script>
    
</head>
<body>
<div id="pagewidth" >
	<div id="header" >
	
		<?PHP include_once("layout/header.html"); ?>
		
	</div>
			<div id="wrapper" class="clearfix" > 
			<div id="maincol" >
					
						<table cellpadding="5" cellspacing="0" bgcolor="#FFFFFF">
							<tr>
								<td align="center"><h2>Weekly Breakdown</h2></td>
							</tr>
							<tr>
							<td class="bluebg">
						<?php
						dbConnect();
						//check to see if a Weeknum value was passed, if not, set WeekNum to CurrWeek.
						if (($Weeknum == NULL) || ($Weeknum == ""))
						{
							$Weeknum = getWeek("AFL");
								
							//check to make sure $Weeknum > 1 AND $Weeknum < 21
							$Weeknum = checkWeekBounds($Weeknum);
							
							if ((date("w")==2)||(date("w")==3)) //If Tuesday or Wednesday, set Weeknum back one week to review scores.
								if ($Weeknum >= 2)
									$Weeknum--;
										
							if (($Weeknum > 17) && (date("w")==1)) //During Playoff time set Weeknum back one week to review scores on Monday also.
								$Weeknum--;
								
						}
						
						//Write SQL Query to extract specified data
						//$SQL = "SELECT * FROM AFLSchedule Where (WEEK=".$Weeknum.") AND (Winner != '-')";
						//Open Record Set using SQL Query
						//$result = mysql_query($SQL) or die("Cannot query the database.<br>");
						?>
						<form action="<? echo $PHP_SELF; ?>" method="POST" name="WeekForm">
						<table bgcolor="#FFFFFF" callpadding="5" cellspacing="0" width="100%" align="center"><tr>
						<tr><td align="center"><H1><?	getWeekBanner($Weeknum, "AFL")	?> Results</H1></td>
						<td width="240" align="right" valign="top"><a href="<? echo $PHP_SELF; ?>?Weeknum=<? echo $Weeknum-1; ?>" class="permLink">Prev</a> | <a href="<? echo $PHP_SELF; ?>?Weeknum=<? echo $Weeknum+1; ?>" class="permLink">Next</a> &nbsp; or &nbsp; 
							<B>Go to:</B><?	WeekDropDown($Weeknum)	?>
						</td>
						</tr>
						</table>
						</form>
						
						<table bgcolor="#FFFFFF" border="1" callpadding="5" cellspacing="0" width="100%" align="center">
						<?
						$query="SELECT * FROM AFLSchedule Where (WEEK=".$Weeknum.") ORDER BY GameNum";
						$doQuery=mysql_query($query);
						$numrows=mysql_num_rows($doQuery);
						$num = 1;
						if($numrows > 0)
						{
							while($results=mysql_fetch_array($doQuery))
							{
								//Fill Arrays With Data
								$homeTeams[$num]=$results['Home'];
								$awayTeams[$num]=$results['Away'];
								$winners[$num]=$results['Winner'];
								$num++;
							}
							
							//Print Away Line
							echo "<tr bgcolor=\"#FFFFFF\"><td><b>Away</b></td>";
							foreach($awayTeams as $team)
								echo "<td width=\"40\" align=\"center\"><img src=\"http://football.joshhughes.com/AFL/images/small/".$team.".gif\" alt=\"".$team."\"  title=\"".$team."\" border=\"0\" /></td>";
							echo "<td class=\"underlinecell\" rowspan=\"3\" valign=\"center\" align=\"center\"><b>Week<br/>$Weeknum<br/>Score</b></td>
								<td class=\"underlinecell\" rowspan=\"3\" valign=\"center\" align=\"center\"><b>Magic<br/>#<br/>
								</b></td></tr>";
							
							//Print @ Line
							echo "<tr bgcolor=\"#FFFFFF\"><td>&nbsp;</td>";
							foreach($homeTeams as $team)
							  echo "<td width=\"40\" align=\"center\">@</td>";
							echo "</tr>";
							
							//Print Home Line
							echo "<tr bgcolor=\"#FFFFFF\" bordercolor=\"#172693\"><td class=\"underlinecell\"><b>Home</b></td>";
							foreach($homeTeams as $team)
							  echo "<td class=\"underlinecell\" width=\"40\" align=\"center\"><img src=\"http://football.joshhughes.com/AFL/images/small/".$team.".gif\" alt=\"".$team."\"  title=\"".$team."\" border=\"0\" /></td>";
							echo "</tr>";
							
							$cols = $numrows + 3;
							
							//Print Winner Line
							echo "<tr bgcolor=\"#FFFFFF\"><td class=\"underlinecell\"><span style=\"color: rgb(255, 0, 0); font-weight: bold;\">Winner</span></td>";
							foreach($winners as $team)
								if($team != "-")
									echo "<td class=\"underlinecell\" width=\"40\" align=\"center\"><img src=\"http://football.joshhughes.com/AFL/images/small/".$team.".gif\" alt=\"".$team."\"  title=\"".$team."\" border=\"0\" /></td>";
								else
									echo "<td class=\"underlinecell\" width=\"40\" align=\"center\">&nbsp;</td>";
							echo "<td class=\"underlinecell\">&nbsp;</td><td class=\"underlinecell\" width=\"40\" align=\"center\"><b>".getMagicNum($Weeknum,"AFL")."</b></td></tr>";
							//Print Rows For User & Picks
							
							$numCorrectPicks = array_fill(1,$numrows, 0);
							$IDs[] = 0;
							$WeeklyScores[] = 0;
							$breakdownString[] = "";
							$totalScore = 0;						
							$totalGuess = 0;
							//Get Data From Users Who Picked
							$UserPickedSQL = "SELECT AFLPicks.*, Users.ID FROM AFLPicks, Users WHERE (AFLPicks.Week = ".$Weeknum." AND AFLPicks.UserID = Users.ID AND (AFLPicks.Game1 IS NOT NULL OR AFLPicks.Game2 IS NOT NULL OR AFLPicks.Game3 IS NOT NULL OR AFLPicks.Game4 IS NOT NULL OR AFLPicks.Game5 IS NOT NULL OR AFLPicks.Game6 IS NOT NULL OR AFLPicks.Game7 IS NOT NULL OR AFLPicks.Game8 IS NOT NULL)) ORDER BY AFLPicks.UserID ASC";
													
							//echo "here??$UserPickedSQL<br/>";
							$UserPickedresult = mysql_query($UserPickedSQL) or die("Cannot query the database for user picks.<br>");
							$row = 0;
							do{
								if ($myrow["UserID"] != NULL)
								{									
									//$breakdownString[$row] = "<td><a href=\"members.php?ID=".$myrow["UserID"]."\" class=\"permLink\" title=\"See the profile on ".$myrow["username"]."\">".$myrow["username"]."</a></td>\n";
									$breakdownString[$row] = "<td>".makeUserLink($myrow["UserID"])."</td>\n";
									$WeeklyScores[$row] = 0;
									$IDs[$row] = $myrow["UserID"];
									for($j = 1; $j <= $numrows; $j++)
									{
										$pick = $myrow["Game".$j];
						
										if($winners[$j] != "-")
										{
											if($pick == $winners[$j])
											{
												$breakdownString[$row].= "<td width=\"40\" align=\"center\"><img src=\"http://football.joshhughes.com/AFL/images/small/".$pick.".gif\" alt=\"".$pick."\" title=\"".$pick."\" border=\"0\" /></td>\n";
												$WeeklyScores[$row]++;
												$numCorrectPicks[$j]++;
											}
											else
											{	
												if($pick == "")
													$breakdownString[$row].= "<td width=\"40\" align=\"center\">&nbsp;</td>\n";
												else
													$breakdownString[$row].= "<td width=\"40\" align=\"center\"><img src=\"http://football.joshhughes.com/AFL/images/red-x.gif\" /></td>\n";
											}
										}
										else
										{
											$InProgressResult = mysql_query("SELECT PickEmailed FROM AFLSchedule WHERE Week=".$Weeknum." AND GameNum=".$j) or die("Cannot query the database for in progress results.<br>");
											$ProgressRow = mysql_fetch_array($InProgressResult);
											if($ProgressRow["PickEmailed"] == 1)
												$breakdownString[$row].= "<td width=\"40\" align=\"center\"><img src=\"http://football.joshhughes.com/AFL/images/small/".$pick.".gif\" alt=\"".$pick."\" title=\"".$pick."\" border=\"0\" /></td>\n";
											else
												$breakdownString[$row].= "<td width=\"40\" align=\"center\">&nbsp;</td>\n";
										}
										
									}
									$breakdownString[$row].= "<td align=\"center\"><span style=\"color: rgb(255, 0, 0); font-weight: bold; font-size: 16px;\">$WeeklyScores[$row]</span></td>\n";
									if (AllGamesStarted($Weeknum,"AFL"))
									{
										$breakdownString[$row].= "<td align=\"center\">";
										if ($myrow["MagicNum"] > 0)
											$breakdownString[$row].= $myrow["MagicNum"];
										else
											$breakdownString[$row].= "-";
										$breakdownString[$row].= "</td></tr>\n";
										$totalGuess += $myrow["MagicNum"];
									}
									else
									{
										$breakdownString[$row].= "<td align=\"center\">-</td></tr>\n";
									}
									$totalScore += $WeeklyScores[$row];
									$row++;
								}
								
							}while($myrow = mysql_fetch_array($UserPickedresult));
							// Sort by weekly score
							for($i=sizeof($WeeklyScores); $i>0 /*>= not needed*/; $i--)
							{
								for($i2=1; $i2 <= $i /*<= so includes last*/; $i2++)
								{
									if($WeeklyScores[$i2-1] < $WeeklyScores[$i2])
									{
										swapthese($WeeklyScores[$i2-1],$WeeklyScores[$i2]);
										swapthese($breakdownString[$i2-1],$breakdownString[$i2]);
										swapthese($IDs[$i2-1],$IDs[$i2]);
									};
									
								}
							}
							// PRint the lines
							for ($num = 0; $num <= sizeof($breakdownString); $num++)
							{
								if ($userID)
								{
									if ($userID == $IDs[$num])
										echo "<tr bgcolor=\"#ffff33\">".$breakdownString[$num];
									else
										echo "<tr bgcolor=\"".getRowColor($num)."\">".$breakdownString[$num];
								}
								else
								{
									echo "<tr bgcolor=\"".getRowColor($num)."\">".$breakdownString[$num];
								}
							}
							
							// Print last rows of table
							echo "<tr bgcolor=\"".getRowColor($row)."\">";
							echo "<td class=\"overlinecell\" align=\"right\"><b>Total</b><br/>($row users)</td>\n";
							for ($j = 1; $j <= $numrows; $j++)
								echo "<td class=\"overlinecell\" width=\"40\" align=\"center\">$numCorrectPicks[$j]</td>\n";
							echo "<td class=\"overlinecell\" align=\"center\"><b>Avg</b><br/>".round($totalScore/$row, 1)."</td>\n";
							echo "<td class=\"overlinecell\" align=\"center\"><b>Avg</b><br/>".round($totalGuess/$row, 1)."</td>\n";
							echo "</tr>\n";
						}
						else
						{
							print '<tr bgcolor=\"#FFFFFF\"><td colspan=\"$cols\" align=\"center\">No Games Set for This Week Yet.</td></tr>';
						}
						//Close table
						echo "</table>";
						?>
						</td>
						<tr><td>&nbsp;</td></tr>
						<tr><td>
						<div class="redbg" style="padding: 2px;">
							<table width="100%" cellpadding="0" cellspacing="0" border="0">
								<tr>
									<td align="left"><span class="whitelink">View Game Scores</span></td>
									<td align="right"><img src="http://football.joshhughes.com/images/showhide.gif" title="Show/Hide Scores" alt="Show/Hide Scores" border="0"  onclick="new Effect.toggle('scoresframe', 'blind');" /></td>
								</tr>
							</table><iframe style="display:none;" id="scoresframe" name="scoresframe" src="http://football.joshhughes.com/AFL/rss/<?= getSeasonYear("AFL"); ?>/week<?= $Weeknum; ?>.xml" height="250" width="100%" frameborder="0" scrolling="no" ></iframe>
						</div>
						</td></tr>
						</tr>
						</table><br/>
			
			</div>
			<div id="leftcol" >
			
				<?PHP include_once("layout/left_column.php"); ?>
		
			</div>
			
		</div>
		
		<div id="footer" >
		
			<?PHP include_once("layout/footer.html"); ?>
			
		</div>
</div>
  </body>
</html>